package webEquipeRechercheGwt.client.entityShowingPanel.linkCreationPanel.person;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import webEquipeRechercheGwt.client.callback.consultation.CallBackGetAllTeam;
import webEquipeRechercheGwt.client.callback.consultation.commands.CommandGetAllTeamsImplToTeamLinkPanel;
import webEquipeRechercheGwt.client.entityMirror.TeamMirror;
import webEquipeRechercheGwt.client.entityShowingPanel.PersonPanel;
import webEquipeRechercheGwt.client.entityShowingPanel.linkCreationPanel.ToTeamLinkCreationPanel;
import webEquipeRechercheGwt.client.handler.creation.link.person.ClickHandlerPersonToTeamLink;
import webEquipeRechercheGwt.client.services.TeamService;
import webEquipeRechercheGwt.client.services.TeamServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;

public class PersonToTeamLinkCreationPanel extends HorizontalPanel implements
		ToTeamLinkCreationPanel {

	private PersonPanel origine;
	private List<TeamMirror> teams;
	private ListBox listBox;
	private Button validation;
	
	public PersonToTeamLinkCreationPanel(PersonPanel origine){
		super();
		this.origine = origine;
		teams = new ArrayList<TeamMirror>();
		listBox = new ListBox();
		listBox.setVisibleItemCount(1);
		validation = new Button("Create link");
		validation.addClickHandler(new ClickHandlerPersonToTeamLink(teams, listBox, origine.getMirror(), origine.getMainPanel()));
	}
	
	private void loadAllPersons(){
		TeamServiceAsync service = GWT.create(TeamService.class);
		AsyncCallback<Collection<TeamMirror>> callback = new CallBackGetAllTeam(new CommandGetAllTeamsImplToTeamLinkPanel(this));
		service.getTeams(callback);
	}
	
	public void setTeams(Collection<TeamMirror> result){
		teams.clear();
		teams.addAll(result);
		teams.removeAll(origine.getMirror().getTeams());
		updateSelection();
	}
	
	private void updateSelection(){
		listBox.clear();
		for(TeamMirror t : teams){
			listBox.addItem(t.getName());
		}
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		add(listBox);
		add(validation);
		loadAllPersons();
	}

}